package com.zoo.springbootinit.canal;

import com.zoo.springbootinit.exception.esdao.PostEsDao;
import com.zoo.springbootinit.model.dto.post.PostEsDTO;
import com.zoo.springbootinit.model.entity.Post;
import com.zoo.springbootinit.service.PostService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Component
public class OnceMysql2Es {

    @Autowired
    PostService postService;
    @Autowired
    PostEsDao postEsDao;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    //开关
    @Value("${fullSyncEnabled}")
    private boolean fullSyncEnabled;

    @PostConstruct
    private void OnceSync() {
        if (fullSyncEnabled) {
            List<Post> posts = postService.getAllPosts();
            Collection<PostEsDTO> postEsDTOS = new ArrayList<>();
            for (Post post : posts) {
                PostEsDTO postEsDTO = new PostEsDTO();
                postEsDTO.setId(post.getId());
                postEsDTO.setTitle(post.getTitle());
                postEsDTO.setContent(post.getContent());
                String newTag = post.getTags().replace("[", "").replace("]", "").replace("\"", "");
                postEsDTO.setTags(Arrays.asList(StringUtils.split(newTag, ',')));
                postEsDTO.setThumbNum(post.getThumbNum());
                postEsDTO.setFavourNum(post.getFavourNum());
                postEsDTO.setUserId(post.getUserId());
                postEsDTO.setCreateTime(post.getCreateTime());
                postEsDTO.setUpdateTime(post.getUpdateTime());
                postEsDTO.setIsDelete(post.getIsDelete());
                postEsDTOS.add(postEsDTO);
            }

            elasticsearchRestTemplate.save(postEsDTOS);
        }

    }
}
